package com.example.contentprovider;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.tbruyelle.rxpermissions3.RxPermissions;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private EditText editText;
    private Button button;
    private TextView textView;
    private String number;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         editText = findViewById(R.id.edi_chaxun);
         button = findViewById(R.id.but_chaxun);
         textView = findViewById(R.id.tv_sousuoneirong);

         button.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
                 textView.setText(chaxun(editText.getText().toString()));
             }
         });

        new RxPermissions(this).request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_SMS,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_CONTACTS)
                .subscribe(new io.reactivex.rxjava3.functions.Consumer<Boolean>() {

                    //aBoolean 请求的权限是否全部同意返回true
                    //若多个权限中有一个权限未同意，侧返回false
                    @Override
                    public void accept(Boolean aBoolean) throws Throwable {
                        if (aBoolean) {
                            //已授权
                        } else {
                            //未授权
                        }
                    }
                });

//        initduanxin();
//        inithaoma();
        initchaxun();
        initc();

    }
    private void  initduanxin()
    {
        //content:///sms
        ContentResolver contentResolver = getContentResolver();
        //获取的是那些列的值
        Cursor cursor = contentResolver.query(Telephony.Sms.CONTENT_URI,new String[]{
                Telephony.Sms.ADDRESS, Telephony.Sms.DATE, Telephony.Sms.TYPE, Telephony.Sms.BODY},
                null,null,null);
        if (cursor.getCount() > 0 )
        {
            //游标置顶
            cursor.moveToFirst();

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
            do {
                String address = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS));
                String date = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.DATE));
                String type = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.TYPE));
                String body = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.BODY));

                Log.d(TAG, "短信地址:" + address + "短信日期:" + simpleDateFormat.format(new Date(Long.parseLong(date))) + "收件类型:" + (Integer.parseInt(type) == 1 ? "发送" : "接收") + "内容：" + body);

            } while (cursor.moveToNext());
        }
        cursor.close();
    }
    private void inithaoma()
    {
        
        
        //1.查询raw_contacts表获得联系人的id
        ContentResolver contentResolver = getContentResolver();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        //2.查询联系人数据
        Cursor cursor = contentResolver.query(uri,null,null,null,null);
        while (cursor.moveToNext()) {
            //获取联系人姓名，手机号码
            @SuppressLint("Range")
            String cName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            @SuppressLint("Range")
            String cNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Log.d(TAG, "姓名：" + cName + " 号码：" + cNum);
        }
        while (cursor.moveToNext()) ;
        cursor.close();
    }
    private void initchaxun()
    {
//        "content://com.android.contacts/data/phones/filter/"
        Uri uri = Uri.parse(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI + "/" +number);
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(uri,new String[]{
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},null,null,null);
        if (cursor.moveToFirst())
        {
            String name = cursor.getString(0);
            Log.d(TAG, number + "对应联系人名称: " + name);
        }
        cursor.close();
    }
    private String chaxun(String numberorname) {


        Uri uri = Uri.parse(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI + "/"+numberorname);
        ContentResolver contentResolver = getContentResolver();
        StringBuffer stringBuffer = new StringBuffer();
        Cursor cursor = contentResolver.query(uri, new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Phone.NUMBER},
                null, null, null);

        if (cursor.moveToFirst()){
            String cName = cursor.getString(0);
            String cNum = cursor.getString(1);
            stringBuffer.append("联系人").append(cName).append("\n").append("电话").append(cNum).append("\t");
        }
        cursor.close();
        return stringBuffer.toString();
    }
    private void initc(){
        //无关联账户:IMTI
        ContentProviderOperation op1 = ContentProviderOperation
                .newInsert(ContactsContract.RawContacts.CONTENT_URI)
                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME,"IMTI")
                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE,"com.example.cantentproviden")
                .withValue(ContactsContract.RawContacts.AGGREGATION_MODE,
                        ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED)
                .build();

        //设置基础设置（姓名）:李桑
        ContentProviderOperation op2 = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Contacts.Photo.RAW_CONTACT_ID,
                        0)
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "熊大")
                .build();
        //设置电话号码Phone:18888888888
        ContentProviderOperation op3 = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID,
                        0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,"11154876764")
                .withValue(ContactsContract.Data.IS_PRIMARY,"1")
                .build();
        //设置邮箱号码Email:317449557@qq.com
        ContentProviderOperation op4 = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Contacts.Entity.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.CommonDataKinds.Email.MIMETYPE,
                        ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Email.DATA,"7654321@qq.com")
                .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
                        ContactsContract.CommonDataKinds.Email.TYPE_MOBILE)
                .build();

        ArrayList<ContentProviderOperation> operations = new ArrayList<>();
        //无关联账号
        operations.add(op1);
        //设置基础设置（姓名）
        operations.add(op2);
        //设置电话号码Phone
        operations.add(op3);
        //设置邮箱号码Email
        operations.add(op4);

        try {
            getContentResolver().applyBatch(ContactsContract.AUTHORITY,operations);
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

}